﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Orange.Logistics.Models;
using System.Text;
using System.Data.SqlClient;

namespace Orange.Logistics.Services {

    public interface IModuleService : IBaseService<Module> {
        IEnumerable<Module> GetModules(Func<Module, bool> filter);
        IEnumerable<Menu> GetSysMenus(int[] roles);
    }

    public class ModuleService : BaseService<Module>, IModuleService {

        //GetParentMenu
        public IEnumerable<Module> GetModules(Func<Module, bool> filter) {
            return db.Modules.Where(filter);
        }

        public IEnumerable<Menu> GetSysMenus(int[] roles) {
            IEnumerable<Module> modules = null;
            if (roles.Contains(1)) {
                modules = GetModules(m => m.Status != "D").OrderBy(m => m.Sort);
            } else {
                modules = (from rp in db.RolePermissions
                           join mp in db.ModulePermissions on rp.PermissionID equals mp.PermissionID
                           join m in db.Modules on mp.ModuleID equals m.Id
                           where roles.Contains(rp.RoleID)
                           where m.Status != "D"
                           orderby m.Sort
                           select m).ToList();
            }

            return modules.Where(m => m.ParentId == 0)
                          .Select(m => new Menu {
                              MenuName = m.ModuleName,
                              Order = m.Sort,
                              SubMenus = modules.Where(t => t.ParentId == m.Id)
                                              .Select(t => new Menu {
                                                  MenuIcon = t.ModuleIcon,
                                                  MenuUrl = "~/" + t.ModuleController + "/Index",
                                                  MenuName = t.ModuleName,
                                                  MenuNo = t.ModuleController,
                                                  Order = t.Sort,
                                              })
                          });
        }

        private Menu ConvertToMenu(Module m) {
            return new Menu {
                MenuIcon = m.ModuleIcon,
                SubMenus = new List<Menu>(),
                MenuUrl = "~/" + m.ModuleController + "/Index",
                MenuName = m.ModuleName,
                MenuNo = m.ModuleController,
                Order = m.Sort
            };
        }
    }
}